<template>
  <el-dialog
    v-model="dialogVisible"
    title="节点信息"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="form-group">
      <label>节点名称</label>
      <el-input v-model="nodeData.name" />
    </div>
    <div class="form-group">
      <label>输入</label>
      <el-input
        type="textarea"
        v-model="nodeData.input"
        :rows="2"
        placeholder="请输入数据"
      />
    </div>
    <div class="form-group">
      <label>节点类型</label>
      <el-select v-model="nodeData.type" placeholder="请选择节点类型" @change="handleTypeChange">
        <el-option
          v-for="option in nodeOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </div>
    <el-card class="form-card" v-if="nodeData.type !== 'nodata'">
      <div v-if="nodeData.type === 'request'" class="http-node-form">
        <div class="form-group">
          <label>请求方法</label>
          <el-select v-model="nodeData.content.method" placeholder="选择请求方法">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </div>
        <div class="form-group">
          <label>URL</label>
          <el-input v-model="nodeData.content.url" placeholder="请输入请求URL" />
        </div>
        <div class="form-group">
          <label>请求头</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.headers"
            placeholder="请输入请求头（JSON格式）"
            :rows="3"
          />
        </div>
        <div class="form-group">
          <label>请求体</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.body"
            placeholder="请输入请求体（JSON格式）"
            :rows="3"
          />
        </div>
      </div>
      <div v-if="nodeData.type === 'js'" class="js-form">
        <div class="form-group">
          <label>JavaScript代码</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.code"
            placeholder="请输入JavaScript代码"
            :rows="6"
          />
        </div>
      </div>
      <div v-if="nodeData.type === 'static'" class="static-form">
        <div class="form-group">
          <label>固定内容</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.text"
            placeholder="请输入固定内容"
            :rows="6"
          />
        </div>
      </div>
      <div v-if="nodeData.type === 'append'" class="append-form">
        <div class="form-group">
          <label>分隔符</label>
          <el-input
            v-model="nodeData.content.separator"
            placeholder="请输入分隔符，如：————————————"
          />
        </div>
        <div class="form-group">
          <label>追加内容</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.text"
            placeholder="请输入要追加的内容"
            :rows="6"
          />
        </div>
      </div>
      <template v-if="nodeData.type === 'ai'">
        <div class="form-group">
          <label>提示词</label>
          <el-input
            type="textarea"
            v-model="nodeData.content.prompt"
            :rows="3"
            placeholder="请输入提示词"
          />
        </div>
        <div class="form-group">
          <label>模型</label>
          <el-input
            v-model="nodeData.content.model"
            placeholder="请输入模型名称"
          />
        </div>
        <div class="form-group">
          <label>Temperature ({{ nodeData.content.temperature }})</label>
          <el-slider
            v-model="nodeData.content.temperature"
            :min="0"
            :max="2"
            :step="0.1"
          />
        </div>
        <div class="form-group">
          <label>Top P ({{ nodeData.content.top_p }})</label>
          <el-slider
            v-model="nodeData.content.top_p"
            :min="0"
            :max="1"
            :step="0.1"
          />
        </div>
        <div class="form-group">
          <label>API 地址</label>
          <el-input
            v-model="nodeData.content.baseURL"
            placeholder="请输入 API 地址"
          />
        </div>
        <div class="form-group">
          <label>API Key</label>
          <el-input
            v-model="nodeData.content.apiKey"
            type="password"
            placeholder="请输入 API Key"
            show-password
          />
        </div>
        <div class="form-group">
          <el-checkbox v-model="nodeData.content.streamResponse">
            流式输出
          </el-checkbox>
        </div>
      </template>
    </el-card>
    <div class="form-group">
      <label>输出</label>
      <div class="output-wrapper">
        <el-input
          type="textarea"
          v-model="nodeData.output"
          :rows="2"
          placeholder="输出数据"
          readonly
        />
        <el-button
          v-if="nodeData.output"
          type="primary"
          size="small"
          class="copy-btn"
          @click="copyOutput"
        >
          复制
        </el-button>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNode">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { useAppStore } from '../stores/appStore';
import { useNodeLibraryStore } from '../stores/nodeLibraryStore.js';
import { nodeOptions } from '../stores/baseData';
import { ElMessage } from 'element-plus';
import { v4 as uuidv4 } from 'uuid';

const store = useAppStore();
const nodeLibraryStore = useNodeLibraryStore();
const nodeData = ref({});
const dialogVisible = ref(false);
const dialogType = ref('add');
const nodeIndex = ref(null);
const workflow = ref(null);

const openDialog = (type, workflowData, data, index) => {
  // type: add edit addToTemplate

  dialogVisible.value = true;
  dialogType.value = type;
  workflow.value = workflowData;
  nodeIndex.value = index;

  if (type === 'edit') {
    nodeData.value = JSON.parse(JSON.stringify(data)); // 深拷贝防止直接修改原数据
  } else {
    nodeData.value = {
      id: uuidv4(),
      name: '',
      input: '',
      type: 'static',
      content: {
        text: ''
      },
      output: '',
      status: '未执行'
    };
  }
};

const closeDialog = () => {
  dialogVisible.value = false;
};

const handleTypeChange = () => {
  switch (nodeData.value.type) {
    case 'request':
      nodeData.value.content = {
        method: 'GET',
        url: '',
        headers: '',
        body: ''
      };
      break;
    case 'js':
      nodeData.value.content = {
        code: ''
      };
      break;
    case 'static':
      nodeData.value.content = {
        text: ''
      };
      break;
    case 'ai':
      nodeData.value.content = {
        prompt: '',
        model: 'deepseek-ai/deepseek-r1',
        temperature: 1.0,
        top_p: 0.9,
        baseURL: 'https://your-ai-service.com/v1',
        apiKey: '',
        streamResponse: true
      };
      break;
    case 'append':
      nodeData.value.content = {
        separator: '————————————',
        text: ''
      };
      break;
    default:
      nodeData.value.content = {};
      break;
  }
};

const saveNode = async () => {
  try {
    switch (dialogType.value) {
      case 'add':
        if (!workflow.value) {
          ElMessage.error('未找到工作流');
          return;
        }
        if (nodeIndex.value !== null && nodeIndex.value !== undefined) {
          const targetNodeId = workflow.value.nodes[nodeIndex.value]?.id;
          if (targetNodeId) {
            await store.insertNodeAfter(workflow.value.id, targetNodeId, nodeData.value);
          } else {
            await store.addNode(workflow.value, nodeData.value);
          }
        } else {
          await store.addNode(workflow.value, nodeData.value);
        }
        break;
      case 'edit':
        if (workflow.value) {
          await store.updateNode(workflow.value.id, nodeData.value.id, nodeData.value);
        } else {
          await nodeLibraryStore.addTemplate(nodeData.value);
        }
        break;
      case 'addToTemplate':
        await nodeLibraryStore.addTemplate(nodeData.value);
        break;
    }

    dialogVisible.value = false;
    ElMessage.success(
      dialogType.value === 'add' 
        ? '添加成功' 
        : dialogType.value === 'edit' 
          ? '更新成功' 
          : '保存成功'
    );
  } catch (error) {
    console.error('保存节点失败:', error);
    ElMessage.error('保存失败');
  }
};

const copyOutput = async () => {
  try {
    await navigator.clipboard.writeText(nodeData.value.output)
    ElMessage.success('复制成功')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}

defineExpose({
  openDialog,
  closeDialog
});
</script>

<style scoped>
.form-group {
  margin-bottom: 16px;
}

.output-wrapper {
  position: relative;
}

.copy-btn {
  position: absolute;
  right: 8px;
  top: 8px;
  z-index: 1;
}
</style>
